package com.example.musicplayer.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.musicplayer.R;
import com.example.musicplayer.activity.MainActivity;
import com.example.musicplayer.activity.MusicActivity;
import com.example.musicplayer.activity.PlayerActivity;
import com.example.musicplayer.adapter.MainTabMyAdapter;
import com.example.musicplayer.adapter.MusicListAdapter;
import com.example.musicplayer.bean.Album;
import com.example.musicplayer.bean.Song;
import com.example.musicplayer.utils.Data;
import com.example.musicplayer.utils.MusicUtils;


import org.jetbrains.annotations.NotNull;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MainTabMyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainTabMyFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private MainTabMyAdapter adapter;

    public MainTabMyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainTabFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainTabMyFragment newInstance(String param1, String param2) {
        MainTabMyFragment fragment = new MainTabMyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    ImageView iv_fragment_my_new_album;

    @Override
    public void onResume() {
        super.onResume();
        try {
            albumList.clear();
            Album local = getDefaultAlbum();
            albumList.add(local);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
            getNetWorkAlbum();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    ImageView iv_fragment_my_fm;
    ImageView iv_fragment_my_love;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //初始化组件
        listView = (ListView)getView().findViewById(R.id.list_main_fragment_songlist);

        //我喜欢跳转
        iv_fragment_my_love = (ImageView)getView().findViewById(R.id.iv_fragment_my_love);
        iv_fragment_my_love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MusicActivity.class);
                intent.putExtra("album",(Serializable)loveAlbum);
                intent.putExtra("isWEBAlbum",true);
                startActivity(intent);
            }
        });
        //私人fm跳转
        iv_fragment_my_fm = (ImageView)getView().findViewById(R.id.iv_fragment_my_fm);
        iv_fragment_my_fm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MusicActivity.class);
                intent.putExtra("album",(Serializable)fmAlbum);
                intent.putExtra("isWEBAlbum",true);
                startActivity(intent);
            }
        });

        iv_fragment_my_new_album = (ImageView)getView().findViewById(R.id.iv_fragment_my_new_album);
        iv_fragment_my_new_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final EditText et = new EditText(getContext());
                et.setHint("请输入歌单标题");
                AlertDialog dialog = new AlertDialog.Builder(getContext()).setTitle("新建歌单")    //设置标题
                        .setView(et)
                        .setPositiveButton("提交", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String url = getString(R.string.web_ip)+"/album";
                                final Data data = (Data)getActivity().getApplication();
                                OkHttpClient okHttpClient = new OkHttpClient();
//                                System.out.println(et.getText().toString());
//                                System.out.println(data.getUserID()+"");
                                System.out.println(url);
                                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                                JSONObject json = new JSONObject();
                                try {
                                    json.put("name",et.getText().toString());
                                    json.put("owner", data.getUserID()+"");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                RequestBody body = RequestBody.create(JSON,json.toJSONString()); // new
                                final Request request = new Request.Builder()
                                        .url(url)
                                        .post(body)
                                        .build();
                                Call call = okHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                        Log.d(TAG, "onResponse: 创建歌单失败" );
                                    }

                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                        Log.d(TAG, "onResponse: 创建歌单成功" );
                                        String json = response.body().string();
                                        dialog.cancel();
                                        getActivity().runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    albumList.clear();
                                                    albumList.add(getDefaultAlbum());
                                                    getNetWorkAlbum();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        });
                                        Looper.prepare();
                                        Toast.makeText(getContext(),"创建成功",Toast.LENGTH_LONG).show();
                                        Looper.loop();


                                    }
                                });
                            }
                        })//添加确定按钮
                        .setNegativeButton("取消",null)//添加取消按钮
                        .create();
                dialog.show();

            }
        });




        adapter = new MainTabMyAdapter(this,albumList);
        listView.setAdapter(adapter);
            //点击事件
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(getActivity(), MusicActivity.class);
                    intent.putExtra("album",(Serializable)albumList.get(position));
                    System.out.println(position);
                    if(position>0){
                        intent.putExtra("isWEBAlbum",true);
                    }
                    startActivity(intent);
                }
            });
    }


    //组件
    ListView listView;
    List<Album> albumList = new ArrayList<>();
    Album loveAlbum;
    Album fmAlbum;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main_tab_my, container, false);

    }

    private Album getDefaultAlbum(){
        Album album  = new Album();
        album.setName("本地音乐");
        album.setSongList(MusicUtils.getMusicData(getContext()));
        if(album.getSongList().isEmpty()){
            album.setAlbumCover(getAlbumArt(0));
        }else{
            album.setAlbumCover(getAlbumArt(album.getSongList().get(0).albumId));
        }
        album.setNumber(album.getSongList().size());
        return  album;
    }

    private void getNetWorkAlbum() throws IOException {

        final Request frequest = new Request.Builder()
                .url(getString(R.string.web_ip)+"/songs/all/1")
                .get()
                .build();
        new OkHttpClient().newCall(frequest).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                fmAlbum = new Album();
                fmAlbum.setName("私人FM");
                String json = response.body().string();
                List<HashMap> list =JSON.parseArray(json, HashMap.class);
                List<Song> songList = new ArrayList<Song>();
                for(HashMap k:list){
                    Song oneSong = new Song();
                    oneSong.song = (String)k.get("song");
                    oneSong.singer = (String)k.get("singer");
                    oneSong.duration = (Integer) k.get("duration");
                    oneSong.path = (String) k.get("path");
                    oneSong.albumCoverPath = (String) k.get("album_cover_path");
                    oneSong.id = (Integer) k.get("id");
                    songList.add(oneSong);
                }
                fmAlbum.setSongList(songList);
                if(fmAlbum.getSongList().isEmpty()){
                    fmAlbum.setAlbumCover(getAlbumArt(0));
                }else{
                    String url = getString(R.string.web_ip)+"/cover/"+fmAlbum.getSongList().get(0).id;
                    fmAlbum.setAlbumCover(getImageFromNetByUrl(url));
                }
            }
        });

        Album album  = new Album();
        final Data data = (Data)getActivity().getApplication();
        String url = getString(R.string.web_ip)+"/list/all/"+data.getUserID();
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: 网络请求获取歌单失败");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: 网络请求获取歌单成功" );
//                System.out.println(response.body().string());
                String json = response.body().string();
                List<HashMap> list =JSON.parseArray(json, HashMap.class);
                for(int i=0;i<list.size();i++){
                    Album album  = new Album();
                    album.setName(list.get(i).get("name").toString());
                    album.setNumber(Integer.parseInt(list.get(i).get("number").toString()));
                    String url = getString(R.string.web_ip)+"/songs/all/"+list.get(i).get("id");
                    OkHttpClient okHttpClient = new OkHttpClient();
                    final Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲失败");
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲成功");
                            String json = response.body().string();
                            List<HashMap> list =JSON.parseArray(json, HashMap.class);
                            List<Song> songList = new ArrayList<Song>();
                            for(HashMap k:list){
                                Song oneSong = new Song();
                                oneSong.song = (String)k.get("song");
                                oneSong.singer = (String)k.get("singer");
                                oneSong.duration = (Integer) k.get("duration");
                                oneSong.path = (String) k.get("path");
                                oneSong.albumCoverPath = (String) k.get("album_cover_path");
                                oneSong.id = (Integer) k.get("id");
                                songList.add(oneSong);
                            }
                            album.setSongList(songList);
                            if(album.getSongList().isEmpty()){
                                album.setAlbumCover(getAlbumArt(0));
                            }else{
                                String url = getString(R.string.web_ip)+"/cover/"+album.getSongList().get(0).id;
                                album.setAlbumCover(getImageFromNetByUrl(url));
                            }
                            albumList.add(album);
                            if(album.getName().equals("我喜欢的音乐")){
                                loveAlbum = album;
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                }
                            });

                        }
                    });
                }
            }
        });
    }

    /**
     * 根据专辑ID获取专辑封面图
     * @param album_id 专辑ID
     * @return
     */
    private Bitmap getAlbumArt(long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = getContext().getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.musicpic);
        }
        return bm;
    }

    private  Bitmap getImageFromNetByUrl(final String src){
        try {
            Log.d("FileUtil", src);
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            connection.disconnect();
            return myBitmap;
        } catch (IOException e) {
            // Log exception
            return null;
        }

    }


}